#include "DataLoader.h"
#include <fstream>
#include "CImg.h"
#include "CudaHelpers.h"

using namespace cimg_library;

using std::ifstream;
using std::ios;

void LoadData(string filename, float** data, int& sizeX, int& sizeY, int& sizeZ)
{
	ifstream file(filename.c_str(), ios::in | ios::binary);

	unsigned short header[3];
	file.read((char*)header, 3 * sizeof(unsigned short));

	sizeX = header[0];
	sizeY = header[1];
	sizeZ = header[2];

	int size = header[0] * header[1] * header[2];

	unsigned short* buf = (unsigned short*)malloc(size * sizeof(unsigned short));

	file.read((char*)buf, size * sizeof(unsigned short));

	(*data) = (float*)malloc(size * sizeof(float));

	for(int i = 0;i < size;i++)
	{
		(*data)[i] = min(1.f, max(.0f, ((float)buf[i]) / 255.f));
	}

	free(buf);
}

void LoadTF(string filename, const int TFWeights[10], float** d, int* size)
{
	CImg<unsigned char> tf_b(filename.c_str());
	(*size) = tf_b.width() * 4;
	float* tf = (float*)malloc((*size) * sizeof(float));
	for(int x = 0;x < tf_b.width();x++)
	{
		tf[x * 4 + 0] = ((float)tf_b.atXY(x, 0, 0)) / 255.f;
		tf[x * 4 + 1] = ((float)tf_b.atXY(x, 0, 1)) / 255.f;
		tf[x * 4 + 2] = ((float)tf_b.atXY(x, 0, 2)) / 255.f;
		tf[x * 4 + 3] = ((float)TFWeights[(int)((((float)x) / ((float)tf_b.width())) * 10.f)]) / 255.f;//((float)tf_b.atXY(x, tf_b.height() - 1, 0)) / 255.f;
	}

	//for(int i = 0;i < *size;i++)
		//printf("%f ", tf[i]);
	(*d) = AllocateAndCopy(tf, (*size));
	free(tf);
}

